from fastapi import APIRouter
import json
from pojo.pojo import *
from dbo.dbutil import *
from util.llm import *
app = APIRouter()


@app.post("/createQN")
async def createQN(data:Questionnaire,user:User):
    rs = {"code":200,'msg':"成功",'data':[]}
    # print(data)
    if data.id is None:
        sql = '''
        INSERT INTO questionnaire(title,type,questionList,userId,`desc`)
        VALUES('{}','{}','{}','{}','{}')
        '''.format(data.title,data.type,json.dumps(data.questionList,ensure_ascii=False),user.id,data.desc)
    else:
        sql = '''
        UPDATE questionnaire SET title='{}',type='{}',questionList='{}',`desc`='{}' WHERE id = '{}'
        '''.format(data.title,data.type,json.dumps(data.questionList,ensure_ascii=False),data.desc,data.id)
    print(sql)
    data = Mysql().insertDB(sql)
    if data==0:
        rs["code"]=500
        rs["msg"]="创建问卷失败，程序员紧急处理中"
        return rs
    
    return rs



@app.post("/doQN")
async def doQN(data:Questionnaire,user:User):
    rs = {"code":200,'msg':"成功",'data':[]}
    print("data.distributeTaskId:::",data.distributeTaskId)
    report = json.dumps(getExamAna(data.json()),ensure_ascii=False)
    if data.distributeTaskId is None:
        sql = '''
        INSERT INTO questionnairerecord(record,userId,questionnaireId,report,status)
        VALUES('{}','{}','{}','{}',1)
        '''.format(data.json(),user.id,data.id,report)
    else:
        sql = '''
        INSERT INTO questionnairerecord(record,userId,questionnaireId,report,status,distributeTaskId)
        VALUES('{}','{}','{}','{}',1,{})
        '''.format(data.json(),user.id,data.id,report,data.distributeTaskId)
    print(sql)
    data = Mysql().insertDB(sql)
    if data==0:
        rs["code"]=500
        rs["msg"]="填写问卷失败，程序员紧急处理中"
        return rs
    return rs


@app.post("/deleteQNByID")
async def deleteQNByID(data:Questionnaire,user:User):
    rs = {"code":200,'msg':"成功",'data':[]}
    sql = '''
    DELETE FROM questionnaire
    WHERE id = '{}'
    '''.format(data.id)
    print(sql)
    data = Mysql().insertDB(sql)
    if data==0:
        rs["code"]=500
        rs["msg"]="删除问卷失败，程序员紧急处理中"
        return rs
    return rs

@app.post("/deleteQNRecordByID")
async def deleteQNRecordByID(data:QuestionnaireRecord,user:User):
    rs = {"code":200,'msg':"成功",'data':[]}
    sql = '''
    DELETE FROM questionnairerecord
    WHERE id = '{}'
    '''.format(data.id)
    print(sql)
    data = Mysql().insertDB(sql)
    if data==0:
        rs["code"]=500
        rs["msg"]="删除记录失败，程序员紧急处理中"
        return rs
    return rs

@app.post("/getQNType")
async def getQNType():
    rs = {"code":200,'msg':"成功",'data':[]}
    sql = '''
    SELECT * FROM questionnairetype
    '''
    print(sql)
    data = Mysql().selectDB(sql,'many')
    if data is None:
        rs["code"]=500
        rs["msg"]="查询失败，程序员修复中"
        return rs
    rs["data"]=data
    return rs

@app.post("/getQNListByUser")
async def getQNList(user:User):
    rs = {"code":200,'msg':"成功",'data':[]}
    sql = '''
    SELECT * FROM questionnaire 
    JOIN user ON user.id =  questionnaire.userId
    WHERE questionnaire.userId = '{}'
    '''.format(user.id)
    print(sql)
    data = Mysql().selectDB(sql,'many')
    if data is None:
        rs["code"]=500
        rs["msg"]="查询失败，程序员修复中"
        return rs
    for item in data:
        item["questionList"]=json.loads(item["questionList"])
    rs["data"]=data
    return rs

@app.post("/getQNRecordListByUser")
async def getQNRecordListByUser(user:User):
    rs = {"code":200,'msg':"成功",'data':[]}
    sql = '''
    SELECT * FROM questionnairerecord 
    JOIN user ON user.id =  questionnairerecord.userId
    WHERE questionnairerecord.userId = '{}'
    '''.format(user.id)
    print(sql)
    data = Mysql().selectDB(sql,'many')
    if data is None:
        rs["code"]=500
        rs["msg"]="查询失败，程序员修复中"
        return rs
    for item in data:
        try:
            item["record"]=json.loads(item["record"])
            item["report"]=json.loads(item["report"].replace('\n',''))
        except:
            pass
    rs["data"]=data
    return rs

@app.post("/getQNListByForm")
async def getQNListByForm(questionnaire:Questionnaire):
    rs = {"code":200,'msg':"成功",'data':[]}
    sql = '''
    SELECT * FROM questionnaire 
    JOIN user ON user.id =  questionnaire.userId
    WHERE 1=1 
    '''
    if questionnaire.type!='综合':
        sql+='''
         AND questionnaire.type = '{}'
        '''.format(questionnaire.type)
    if questionnaire.title is not None and questionnaire.title!='':
        sql+='''
         AND questionnaire.title like '%{}%'
        '''.format(questionnaire.title)
    print(sql)
    data = Mysql().selectDB(sql,'many')
    if data is None:
        rs["code"]=500
        rs["msg"]="查询失败，程序员修复中"
        return rs
    for item in data:
        item["questionList"]=json.loads(item["questionList"])
    rs["data"]=data
    return rs


@app.post("/getQNByID")
async def getQNByID(questionnaire:Questionnaire):
    # print(user)
    rs = {"code":200,'msg':"成功",'data':[]}
    sql = '''
    SELECT * FROM questionnaire 
    JOIN user ON user.id =  questionnaire.userId
    WHERE questionnaire.id = '{}'
    '''.format(questionnaire.id)
    print(sql)
    data = Mysql().selectDB(sql,'one')
    if data is None:
        rs["code"]=500
        rs["msg"]="查询失败，程序员修复中"
        return rs
    # for item in data:
    data["questionList"]=json.loads(data["questionList"])
    rs["data"]=data
    return rs

@app.post("/getQNRecordByID")
async def getQNRecordByID(questionnaireRecord:QuestionnaireRecord):
    rs = {"code":200,'msg':"成功",'data':[]}
    sql = '''
    SELECT * FROM questionnairerecord 
    JOIN user ON user.id = questionnairerecord.userId
    WHERE questionnairerecord.id = '{}'
    '''.format(questionnaireRecord.id)
    print(sql)
    data = Mysql().selectDB(sql,'one')
    if data is None:
        rs["code"]=500
        rs["msg"]="查询失败，程序员修复中"
        return rs
    
    data["record"]=json.loads(data["record"])
    try:
        data["report"]=json.loads(data["report"].replace('\n',''))
    except Exception as e:
        print(e)
        pass
    rs["data"]=data
    return rs
